//1.引入包
const express=require('express');
const expressStatic=require('express-static');
const slideRouter=require('./routes/slide');
const dbConnect=require('./utils/db/mongodbConnect');
const userRouter=require('./routes/user');
const bodyParser=require('body-parser');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const viewRouter=require('./routes/views');
const childRouter=require('./routes/child');
const womenRouter=require('./routes/women');
const menRouter=require('./routes/mens');
const mobilesRouter=require('./routes/mobiles');

//2.创建服务-->启动服务
var app=express();

app.listen(8080,function (err) {
    if (err){
        console.log('App is error!...');
    }else {
        console.log('App is running!...')
    }
});

//开启数据连接
dbConnect.dbConnect();
// 启用body-parser
app.use(bodyParser.urlencoded({extends:true}));
//启用cookie
var keys=[];
for(var i=0;i<1000;i++){
    var str='abcd133%^&'+Math.random(1000000);
    keys.push(str);
}
app.use(cookieParser());
//session必须用签名
app.use(cookieSession({
    name:'storeOnline',
    keys:keys,
    maxAge:20*60*1000
}))

//启用路由
app.use('/slide',slideRouter.router);
app.use('/user',userRouter.router);
app.use('/views',viewRouter.router);
app.use('/child',childRouter.router);
app.use('/she',womenRouter.router);
app.use('/he',menRouter.router);
app.use('/mob',mobilesRouter.router);

//起始页
//路由链
app.use('/',function (req,res,next) {
    var options = {
        root: __dirname + '/www/',
        dotfiles: 'deny',
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true
        }
    };
    var url=req.url;
    // console.log(url.lastIndexOf('/')+'---------'+url.length);
    // 0---------1
    // 8---------22
    // 14---------32
    // 12---------24
    //......

    //根文件夹与非根的操作
    if (url.indexOf('/')==0 && url.length > 1){
        //不是根文件夹的话放行
        next();
    }else {
        //是根文件夹到默认起始页
        res.sendFile('index.html',options,function (err) {
            if (err){
                console.log('index.html is error!...')
            }
        })
    }

})

//3.静态页面的访问
app.use(expressStatic('./www'));




//F12-->文件出现红色-->Headers-->Status Code:500 Internal Server Error
// 1.没有发出去；
// 2.服务器返回
// 3.缓存中有这个东西